package com.youzhi.backend.controller;

import cn.hutool.core.collection.CollUtil;
import com.youzhi.backend.dto.Page;
import com.youzhi.backend.exception.EcpEnum;
import com.youzhi.backend.exception.YouZhiException;
import com.youzhi.backend.request.PageRequest;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Slf4j
public abstract class BaseController {


    /**
     * 校验字段值是否为空
     *
     * @param o      数据对象
     * @param fields 数据对象的字段值
     */
    public void verifyIfBlank(Object o, String... fields) {
        for (String filed : fields) {
            try {
                Field declaredField = o.getClass().getDeclaredField(filed);
                declaredField.setAccessible(true);
                Object value = declaredField.get(o);
                if (value == null) {
                    throw YouZhiException.newException(EcpEnum.field_no_blank, filed);
                } else if (value instanceof String && ((String) value).length() == 0) {
                    throw YouZhiException.newException(EcpEnum.field_no_blank, filed);
                } else if (value instanceof Collection && ((Collection) value).isEmpty()) {
                    throw YouZhiException.newException(EcpEnum.field_no_blank, filed);
                }
            } catch (Exception e) {
                log.error("校验字段异常 o={},fields={}", o, fields, e);
                //转译为业务异常抛出
                throw translateYouZhiException(e);
            }

        }
    }



    public void verifyListIsEmpty(List list) {
        if (CollUtil.isEmpty(list)) {
            throw YouZhiException.newException(EcpEnum.query_params_is_empty);
        }
    }



    private YouZhiException translateYouZhiException(Exception e) {

        if (e instanceof YouZhiException) {
            return (YouZhiException) e;
        } else {
            return YouZhiException.newUnknownException();
        }

    }


}
